<?php

namespace app\modules\admin\controllers;

use app\common\CommonController;
use app\modules\admin\models\AuthItem;
use Yii;
use yii\helpers\Url;
use app\modules\admin\models\RBAC;
use yii\widgets\ActiveForm;
use yii\web\Response;

class RbacController extends CommonController
{

    public function actionIndex()
    {
        return $this->render('index');
    }

    /**
     * 创建权限节点
     * @return array|string
     */
    public function actionCreatePermission()
    {
        $rbac = new RBAC();
        $rbac->load(\Yii::$app->request->post());
        if (\Yii::$app->request->isAjax)
        {
                Yii::$app->response->format = Response::FORMAT_JSON;
                return ActiveForm::validate($rbac);
        }
        else if(\Yii::$app->request->isPost)
        {
            if (!$rbac->save())
            {
                $message = current($rbac->getFirstErrors());
                $links = [
                    [
                        'name'=>'重新添加',
                        'url'=>Url::toRoute($this->action->id)
                    ]
                ];
                $this->error('操作失败',$message,$links);
            }
            $this->redirect([$this->action->id]);
        }
        else
        {
            return $this->render('create',[
                'model' => $rbac
            ]);
        }
    }

    public function actionCreateRole()
    {
        $rbac = new RBAC();
        $rbac->load(\Yii::$app->request->post());
        if (\Yii::$app->request->isAjax)
        {
            Yii::$app->response->format = Response::FORMAT_JSON;
            return [];
            return ActiveForm::validate($rbac);
        }
        else if(\Yii::$app->request->isPost)
        {
            $message = ActiveForm::validate($rbac);
            if ($message)
            {
                $message = current(current(ActiveForm::validate($rbac)));
                $links = [
                    [
                        'name'=>'重新添加',
                        'url'=>Url::toRoute($this->action->id)
                    ]
                ];
                $this->error('操作失败',$message,$links);
            }
            $rbac->save();
            $this->redirect([$this->action->id]);
        }
        else
        {
            return $this->render('create',[
                'model' => $rbac
            ]);
        }
    }
    
    public function actionPermissionList()
    {
        $list = AuthItem::find()->asArray()->all();
        return $this->render(
            'permission-list'
        );
    }

    public function beforeAction($action)
    {
        parent::beforeAction($action);
        // TODO: Change the autogenerated stub
        RBAC::getCurrentRbacID();
        return true;
    }
}
